//
//  MeViewController.swift
//  ezyform
//
//  Created by MoennigQ on 18/02/2017.
//  Copyright © 2017 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import RxGesture
import HandyJSON
import AVFoundation
import MBProgressHUD
import Photos
enum MeMenuType: Int {
    case profile = 0
    case rewards = 1
    case loginMethod = 2
    case settings = 3
    case logOut = 4
}
struct JobsCntAndReward: HandyJSON {
    var installing: Int?
    var installed: Int?
    var reward: Int?
}
class MeViewController: BaseViewController {
    var firstLoadFlag: Bool = true
    fileprivate lazy var disposeBag = DisposeBag()
    let customView = MeView()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
        self.initData()
        self.getJobsCntAndReward()
    }
    func initUI(){
        self.view = self.customView
        self.customView.setData()
        self.customView.closeBtn.rx.tap.subscribe(onNext: { [weak self] _ in
            self?.navigationController?.popViewController(animated: false)
        }).disposed(by: disposeBag)
        //选择某一行
        self.customView.tableView.rx.itemSelected.bind { [weak self] (indexPath) in
            self?.itemSelected(indexPath.row)
        }.disposed(by: disposeBag)
        self.customView.avatarImageView.rx.tapGesture().when(.recognized).subscribe { [weak self] _ in
            self?.addAvater()
        }.disposed(by: self.disposeBag)
        
        //监听字体变化,埋点
        Constant.standardViewFlagSuject.subscribe {  standardFlag in
            if standardFlag {
                TraceHelper.shared.track(.fontStandard )
            }else{
                TraceHelper.shared.track(.fontLarger)
                
            }
        }.disposed(by: self.disposeBag)
    }
    
    fileprivate func initData(){
        var list: [MeMenuType] = []
        list.append(.profile)
        list.append(.rewards)
        list.append(.settings)
        self.customView.dataObserver.accept(list)
    }
    private func itemSelected(_ row: Int){
        let memuType = self.customView.dataObserver.value[row]
        switch memuType {
        case .profile:
            self.toMyInfomation()
        case .rewards://Installer Points 会员积分
            self.toRewards()
        case .settings:
            self.toSettings()
        default:
            break
        }
    }
    //MARK: 多选按钮Add attachment
    fileprivate func addAvater(){
        let cellList = [CellModel(title: CheckListImageFromType.takePhoto.rawValue),CellModel(title: CheckListImageFromType.chooseFromLibrary.rawValue)]
        let actionSheetView = CustomActionSheet(title: R.string.localizable.setProfilePicture(), aCellArray: cellList, aCancelModel: CellModel(title: R.string.localizable.cancel()), aSelectedClosure: { [weak self](row) in
            guard let strongSelf = self else {return}
            switch cellList[row].title {
            case CheckListImageFromType.takePhoto.rawValue:
                strongSelf.takePhoto()
            case CheckListImageFromType.chooseFromLibrary.rawValue:
                strongSelf.selectFromPhotosLibrary()
            default:
                break
            } 
        }, aCancelClosure: nil)
        self.view.addSubview(actionSheetView)
    }
    //MARK: - 选择图片
    private func selectFromPhotosLibrary(){
        PhotosManager.shared.initData(vc: self, maxCount: 1, closure: {[weak self] (assert, errmsg) in
            if let _ = errmsg{
                Tool().showAlertViewWithOneBtn(message: errmsg!)
            }else if let assert = assert as? PHAsset{
                if let data = PhotosManager.shared.getImageDataFromAssert(assert){
                    self?.uploadAvatar(data)
                }
            }
        }).getPhotos()
    }
    //MARK: - 拍照
    private func takePhoto(){
        AVCaptureDevice.requestAccess(for: AVMediaType.video) { (status) in
            DispatchQueue.main.async {
                if status {
                    let vc = TakePhotoViewController()
                    vc.defaultUseFrontCameraFlag = true//开启前置摄像头
                    vc.maxCount = 1
                    vc.takePhotoClosure = {[weak self] (image) in
                        let resultData: NSData = MediaUtil().resetSizeOfImageData(source_image: image)
                        //处理并保存图片
                        self?.uploadAvatar(resultData as Data)
                        self?.navigationController?.popViewController(animated: true)
                    }
                    vc.selectPhotosFromLibraryClosure = {[weak self] (phAssert) in
                        if let data = PhotosManager.shared.getImageDataFromAssert(phAssert){
                            self?.uploadAvatar(data)
                        }
                        self?.navigationController?.popViewController(animated: true)
                    }
                    self.navigationController?.pushViewController(vc, animated: true)
                    
                }else{
                    Tool().showAlertViewWithOneBtn(message: NSLocalizedString("camera.permission", comment: ""))
                }
            }
        }
    }
    fileprivate func uploadAvatar(_ imageData: Data){
        
        let vm = MyInformationService()
        vm.setBlockAfterNetwork { (result , _) in
            ModelViewUtil.shared.hideLoadingView()
            if let model = result as? MyInformationModel, model.avatars.thumb_160 != ""{
                APPConfig.loginInfo.avatarURLStr = model.avatars.thumb_160
                Tool().setValueOfUserDefaults(model.avatars.thumb_160, key: APPConfig.LoginUserAvatarKey)
                self.customView.setData()
            }
            MBProgressHUD.showToast(parentView: self.view, text: "Upload Successfully")
        } errorBlock: { code, error in
            ModelViewUtil.shared.hideLoadingView()
            Tool().showErrorInfo(code,error)
        }
        ModelViewUtil.shared.showLoadingView("Uploading...")
        vm.uploadAvatarImage(imageData)
    }
    fileprivate func getJobsCntAndReward(){
        let vm = MyInformationService()
        vm.setBlockAfterNetwork { (result , _) in
            ModelViewUtil.shared.hideLoadingView()
            if let model = result as? JobsCntAndReward{
                self.customView.setJobsCntAndReward(model)
            }
        } errorBlock: { code, error in
            ModelViewUtil.shared.hideLoadingView()
            Tool().showErrorInfo(code,error)
        }
        if firstLoadFlag {//首次加载才显示loading
            firstLoadFlag = false
            ModelViewUtil.shared.showLoadingView()
        }
        vm.getJobsCntAndReward()
    }
    fileprivate func toMyInfomation(){
        let vc = MyInformationViewController()
        //hid tab bar when push
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: false)
    }
    fileprivate func toRewards(){
        let vc = RewardsViewController()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: false)
    }
    private func toSettings(){
        let vc = SettingViewController()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: false)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }
}
